<template>
  <view>
    <view class="list">
      <u-line color="blue" />
      <u-empty v-if="isEmpty" text="暂无任何通知" mode="list"></u-empty>
      <view v-for="(notify,index) in notifyList" :key="index">
        <view class="one" @click="click(notify.type,notify.extend,index,notify.content)">
          <view class="two">
            <view class="name">
              {{ notify.name }}
            </view>
            <view class="tip">
              {{ notify.status | notifyFilter }}
            </view>
            <view class="date">
              {{ notify.gmtCreate | timestampFormat }}
            </view>
          </view>
          <view :class="notify.signFlag === 0 || notify.signFlag == null ? 'point': ''"></view>
          <view class="three">
            {{ notify.content | contentText }}
          </view>
        </view>
        <u-line color="blue" />
      </view>
      <u-loadmore v-if="!isEmpty" :status="status" />
    </view>
  </view>
</template>

<script>
import {timestampFormat} from "../../utils/date";

export default {
  data() {
    return {
      isEmpty: false,
      notifyList: [],
      pageNum: 1,
      total: 0,
      status: 'loadmore',
      // 后端需要修改的状态，资料为4，签到为2
      s: 2
    };
  },
  onLoad(){
    uni.$emit("setVuexUserInfo",{user:null,isLoginPage: false});
    this.initial();
    uni.$on("signNotify",this.signNotify);
    uni.$on("receiveNotifyMsg",this.receiveNotifyMsg);

  },
  onPullDownRefresh() {
    this.initial();
  },
  onReachBottom() {
    this.pageNum = ++ this.pageNum;
    this.status = 'loading';
    if((this.pageNum - 1) * 10 > this.total) {
      setTimeout(() => {
        this.status = 'nomore';
      }, 1000)
    }else {
      this.getNotifyMsg().then(res => {
        this.notifyList = this.notifyList.concat(res.data);
        this.total = res.total;
      })
      this.status = 'loadmore';
    }
  },
  methods:{
    initial(){
      this.pageNum = 1;
      this.total = 0;
      this.getNotifyMsg().then(res => {
        if (res.total === 0){
          this.isEmpty = true;
        }else {
          this.notifyList = res.data;
          this.total = res.total;
        }
        uni.stopPullDownRefresh();
      })
    },
    async getNotifyMsg(){
      return await this.$u.api.queryNotifyMsg(this.pageNum, this.$store.getters.id);
    },
    click(type,extend,index,v){
      if (type === 1){
        this.s = 2;
        this.signIn(extend,index,v);
      }else if (type === 2){
        this.s = 4;
        this.toData(extend,index,v);
      }
    },
    signIn(extend,index,v){
      let arr = extend.split(":");
      let nowDate = new Date();
      let endDate = new Date(Number.parseInt(arr[arr.length - 1]));
      let beginDate = new Date(Number.parseInt(arr[arr.length - 2]));
      if (beginDate > nowDate){
        this.$u.toast("签到未开始！")
      }else if (beginDate <= nowDate && endDate >= nowDate){
        if (this.notifyList[index].status === 1) {
          this.$u.toast("您已签到！");
        }else {
          if (v === '手势') {
            this.toGestureLock(arr, index);
          } else if (v === '扫码') {
            this.signNotify({index: index, status: null});
            this.scan(arr, index);
          } else if (v === '一键') {
            this.oneClick(arr[0], index);
          }
        }
      }else {
        if (this.notifyList[index].status === 1) {
          this.$u.toast("您已签到！")
        }else {
          this.$u.toast("签到已结束！")
          let notifyObj = this.notifyList[index];
          if (
              (
                  notifyObj.status === 5 || notifyObj.status === null
              ) && (
                  notifyObj.signFlag === 0 || notifyObj.signFlag == null
              )) {
            this.signNotify({index: index, status: null});
          }
        }
      }
    },
    scan(arr,index){
      let that = this;
      // #ifdef H5
      this.$u.toast("网页不支持扫码，请打开APP或小程序！")
      // #endif
      // 允许从相机和相册扫码
      // #ifndef H5
      uni.scanCode({
        success: function(res) {
          console.log('条码类型：' + res.scanType);
          console.log('条码内容：' + res.result);
          // 如果是链接直接跳转
          let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
          if (reg.test(res.result)) {
            // #ifdef MP
            that.$u.toast("微信小程序不支持打开网页链接！");
            // #endif
            // #ifndef MP
            void plus.runtime.openWeb(res.result);
            // #endif
          } else {
            let result = res.result.split(":");
            if (result[0] === "feige") {
              if (result[1] === "course" || result[1] === "clazz"){
                that.$u.route({
                  url: 'pages/scan_to/scan_to',
                  params: {
                    type: result[1],
                    id: result[2]
                  }
                })
              }else if (result[1] === "sign") {
                // 发送签到信息给后端
                let data = {
                  signUserId: that.$store.getters.id,
                  signTaskId: arr[0]
                }
                that.$u.api.saveSignIn(data).then(res => {
                  if (res.code === 200) {
                    that.$u.toast('签到成功');
                    that.signNotify({index: index, status: 1})
                  } else {
                    that.$u.toast('签到失败！')
                  }
                })
              }
            } else {
              that.$u.toast("该二维码不合法！");
            }
          }
        }
      });
      // #endif
    },
    oneClick(id,index){
      this.$u.route({
        url: '/pages/one_click_sign_in/one_click_sign_in',
        params: {
          index: index,
          id: id
        }
      })
    },
    toGestureLock(arr,index){
      this.$u.route({
        url: '/pages/gesture_lock/gesture_lock',
        params: {
          password: arr[0],
          index: index,
          id: arr[1]
        }
      });
    },
    toData(path,index,name){
      let lastIndexOf = path.lastIndexOf(".");
      let data = {
        name: name,
        path: path.substr(0,lastIndexOf)
      }
      uni.setStorage({
        key: 'pdf-url',
        data: JSON.stringify(data),
        success: (res) => {
          if (this.notifyList[index].status !== 4){
            this.signNotify({index: index, status: null});
          }
          this.$u.route({
            url: 'pages/show_pdf/show_pdf'
          });
        },
        fail: (err) => {
          console.log(err)
          this.$u.toast("出错啦！");
        }
      })
    },
    signNotify({index, status}){
      let data = {
        notifyMsgId: this.notifyList[index].id,
        userId: this.$store.getters.id,
        status: this.s
      }
      if (status != null){
        data.status = status;
      }else {
        data['signFlag'] = 1;
      }
      // 更新消息为已读
      this.$u.api.updateNotifyMsgUser(data).then(res => {
        if (res.code === 200){
          this.notifyList[index].signFlag = 1;
          this.notifyList[index].status = data.status;
          // 解决dom不更新问题
          this.$set(this.notifyList,index,this.notifyList[index]);
        }
      });

    },
    receiveNotifyMsg(msg){
      this.notifyList.unshift(msg);
      if (this.isEmpty){
        this.isEmpty = false;
      }
    }
  },

  filters: {
    notifyFilter(v){
      if (v === 1){
        return '已签到';
      }else if(v === 2){
        return '未签到';
      }else if (v === 3){
        return '签到失败';
      }else if(v === 4){
        return '已查看';
      }else{
        return '未查看';
      }
    },
    timestampFormat: timestampFormat,
    contentText(v){
      if (v === '手势'){
        return '发布手势密码签到，请点击绘制手势密码';
      }else if (v === '扫码'){
        return '发布二维码签到，请扫描教师提供的二维码签到';
      }else if (v === '一键'){
        return '发布一键签到，请点击签到';
      }else {
        return "发布了" + v + "文件，点击可查看";
      }
    }
  }
}
</script>

<style lang="scss">
.list {
  display: flex;
  flex-direction: column;
  .point {
    background-color: #f74c31;
    line-height: 20rpx;
    text-align: right;
    font-size: 18rpx;
    width: 20rpx;
    height: 20rpx;
    border-radius: 18upx;
    color: #fff;
    right: 60rpx;
    position: absolute;
    margin-top: 80rpx;
  }
  .one {
    width: 100%;
    height: 160rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .two {
      display: flex;
      justify-content: space-between;
      font-weight: bold;
      font-size: 30rpx;
      margin: 20rpx 0 0 30rpx;
      .tip {
        color: $u-type-success;
        font-weight: 10;
        border: 1rpx solid $u-type-success;
      }
      .date {
        margin-right: 20rpx;
      }
    }
    .three {
      font-size: 25rpx;
      margin:0 0 20rpx 30rpx;
    }
  }
}
</style>
